﻿namespace MetaProperties.Framework
{
    using System;
    using System.Linq.Expressions;
    using System.Reflection;

    /// <summary>
    /// Helper class for extracting property information from an expression.
    /// </summary>
    public class PropertyNameHelper
    {
        /// <summary>
        /// Gets the PropertyInfo from the given expression.
        /// </summary>
        /// <typeparam name="TObject">The type of the object.</typeparam>
        /// <typeparam name="T">The type of the value.</typeparam>
        /// <param name="p">The expression for getting the property value.</param>
        /// <returns>The PropertyInfo for the property.</returns>
        public static PropertyInfo GetProperty<TObject, T>(Expression<Func<TObject, T>> p)
        {
            return GetPropertyFromLambdaExpression(p);
        }

        /// <summary>
        /// Gets the PropertyInfo from the given expression.
        /// </summary>
        /// <typeparam name="T">The type of the value.</typeparam>
        /// <param name="p">The expression for getting the property value.</param>
        /// <returns>The PropertyInfo for the property.</returns>
        public static PropertyInfo GetProperty<T>(Expression<Func<T>> p)
        {
            return GetPropertyFromLambdaExpression(p);
        }

        /// <summary>
        /// Gets the PropertyInfo from the given expression.
        /// </summary>
        /// <param name="p">The expression for getting the property value.</param>
        /// <returns>The PropertyInfo for the property.</returns>
        private static PropertyInfo GetPropertyFromLambdaExpression(LambdaExpression p)
        {
            return (PropertyInfo)((MemberExpression)p.Body).Member;
        }
    }
}